package com.sikaryofficial.backend.service.points;

import com.sikaryofficial.backend.constant.RedisCacheKey;
import com.sikaryofficial.backend.service.IPointsDetailStrategy;
import com.sikaryofficial.common.core.constant.PointRuleConstant;
import com.sikaryofficial.common.redis.lock.RedisDistributedLocker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author : qinjinyuan
 * @desc : 扫码任务积分服务
 * @date : 2023/10/31 18:58
 */
@Service(value = PointRuleConstant.SCAN_TASK + IPointsDetailStrategy.SUFFIX)
@Slf4j
public class ScanTaskPointsService extends AbstractPointService {

    @Autowired
    private RedisDistributedLocker distributedLock;

    /**
     * 更新积分明细数据
     *
     * @param sourceId
     * @param userId
     * @param pointsDetailValue
     * @return
     */
    @Override
    public boolean updatePointsByInputValue(Long sourceId, Long userId, Integer pointsDetailValue, String param, String sourceName) {
        String lockKey = "points_lock:user:" + userId;
        // 使用Redis分布式锁或其他锁机制
        if (distributedLock.tryLock(lockKey,  TimeUnit.MILLISECONDS,5000,5000)) { // 5秒超时
            try {
                boolean isOver = checkPointsOver(userId, PointRuleConstant.SCAN_TASK, RedisCacheKey.SCAN_TASK_POINTS_NUM);
                if (!isOver) {
                    this.increasePoints(sourceId, userId, PointRuleConstant.SCAN_TASK, "");
                    this.afterIncrease(userId, RedisCacheKey.SCAN_TASK_POINTS_NUM);
                    return true;
                }
                return false;
            } finally {
                distributedLock.unlock(lockKey);
            }
        } else {
            // 获取锁失败，可选择重试或直接返回
            log.warn("Failed to acquire lock for user: {}", userId);
            return false;
        }
    }
}
